
#include "opend.h"

#define NALLOC 10

// alloc more entries in the client[] array
static void client_alloc(void)
{
    if (NULL == client)
    {
        client = malloc(NALLOC * sizeof(Client));
    }
    else
    {
        client = realloc(client, (client_size+NALLOC)*sizeof(Client));
    }

    if (NULL == client)
    {
        err_sys("can't alloc for client array");
    }

    for (int i = client_size; i < client_size + NALLOC; i++)
    {
        client[i].fd = -1;
    }

    client_size += NALLOC;
}

// Called by loop() when connection request from a new client arrives
int client_add(int fd, uid_t uid)
{
    if (NULL == client)
    {
        client_alloc();
    }

again:
    for (int i = 0; i < client_size; i++)
    {
        if (-1 == client[i].fd)
        {
            client[i].fd = fd;
            client[i].uid = uid;
            return i;
        }
    }

    client_alloc();
    goto again;
}

// Called by loop() when we're done with a client
void client_del(int fd)
{
    for (int i = 0; i < client_size; i++)
    {
        if (fd == client[i].fd)
        {
            client[i].fd = -1;
            return;
        }
    }

    log_quit("can't find client entry for fd %d", fd);
}
